<?php

require_once '../config/controller.php';
require_once '../views/ViewAdminController.php';
require_once '../config/class.mysql.php';
require_once '../config/metadata.php';

class GaleriaController extends Controller {

	protected static $baseUrl = '/panel/galeria.php';

	public function index_action() {
		$data = array('title' => "Gestión galería");
		$metadata = array('title' => "Gestión galería");
		$this->viewController->render('galeria', $data, $metadata);
	}
	public function categorias_action() {
		$categorias = $this->Mysql->getAll('categorias', 'id, nombre, orden', null, 'orden');
		$errorCode = $this->getParam('error');

		$data = array(
			'title' => "Gestión de Categorías",
			'categorias' => $categorias,
			'baseUrl' => self::$baseUrl,
			'error' => $errorCode
		);
		$metadata = array('title' => "Gestión de Categorías");
		$this->viewController->render('categorias', $data, $metadata);
	}

	public function ordenar_action() {
		 if(isset($_POST['orden'])){
		    $result = $this->Mysql->getAll('categorias', 'id, nombre, orden', null, 'orden');
		    for($i=0, $count = count($result); $i<$count; $i++){
			if($_POST["orden".$result[$i]["id"]]!=0){
		            $orden=$_POST["orden".$result[$i]["id"]];
		            $id=$result[$i]["id"];
		            $this->Mysql->update('categorias', array('orden' => $orden), "id='".$id."'");
		        }
		    }
		}
		$this->redirect('categorias');
	}

	public function insertar_action() {
		if(isset($_POST['nombre-cat']) && isset($_POST['orden-cat']) ){
			$this->Mysql->insert('categorias', array($_POST['nombre-cat'], $_POST['orden-cat']+1 ));
		}
		$this->redirect('categorias');
	}

	public function borrar_action() {
		$id = $this->getParam('id');
		$errorMsg = '';
		if ($id) {
			$fotos = $this->Mysql->getWhere('fotos', 'id', array('id_categoria', $id));
			$videos = $this->Mysql->getWhere('videos', 'id', array('id_categoria', $id));
			if(count($fotos)!=0 || count($videos)!=0) { 
				$errorCode = 1;
			} else $this->Mysql->delete('categorias', array('id' => $id));
		}
		$this->redirect('categorias', $errorCode);
	}

	public function editar_action() {
		if(isset($_POST['nombre-edit-cat']) && isset($_POST['id-edit-cat'])){
			$this->Mysql->update('categorias', array('nombre' => $_POST['nombre-edit-cat']), "id='".$_POST['id-edit-cat']."'");
		}
		$this->redirect('categorias');
	}

}

$controller = new GaleriaController('ViewAdminController', true);
$controller->dispatch();
